package cn.xspace.module.other.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xspace.android.xafcommon.util.Constants;

import cn.xspace.library.ui.activity.LoginAct;
import cn.xspace.library.util.MyInfoUtil;
import com.xspace.android.xafcommon.util.PreferencesUtils;

import cn.xspace.module.other.application.MyApplication;
import cn.xspace.module.other.http.RegisterCodeIFHTTP;
import cn.xspace.module.other.http.RegisterHTTP;
import cn.xspace.module.other.http.RegisterPhoneIFHTTP;
import cn.xspace.module.other.util.RProxy;
import cn.xspace.module.other.util.RegusteractCode;

public class RegisterAct2 extends Activity {
	private View phoneIF;
	private EditText edPhone;
	private EditText edPass;
	private EditText edNewPass;
	private EditText edCode;
	private Button submit;
	private ImageView imgCode;
	private boolean[] ifboo = { false, false, false, false };
	private String codeKey;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(RProxy.registeract2);
		TextView title = (TextView) findViewById(RProxy.registeract2_title);
		title.setText("注册");

		iniView();
	}

	private void iniView() {

		// NotEmptyTextWatcher listenerWatcher = new NotEmptyTextWatcher();
		phoneIF = findViewById(RProxy.registeract2_loading_if);

		edPhone = (EditText) findViewById(RProxy.registeract2_input_mobile_edtTxt);
		edPass = (EditText) findViewById(RProxy.registeract2_password_edtTxt);
		edNewPass = (EditText) findViewById(RProxy.registeract2_confirm_password_edtTxt);
		edCode = (EditText) findViewById(RProxy.registeract2_vercode_edtTxt);

		// CheckBox passIF = (CheckBox)
		// findViewById(R.id.registeract_showpwd_chk);

		submit = (Button) findViewById(RProxy.registeract2_register_btn);

		imgCode = (ImageView) findViewById(RProxy.registeract2_vercode_img);
		imgCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ifboo[0]) {
					imgCode.setImageResource(0);
					ifCode();
				}
			}
		});

		edPhone.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (edPhone.getText().toString().length() == 11) {
					phoneIF.setVisibility(View.VISIBLE);
					ifPhone();
				} else {
					phoneIF.setVisibility(View.GONE);
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_not_synced);
					drawable.setBounds(0, 0, 60, 60);
					edPhone.setError("您的手机号不足11位", drawable);
					ifboo[0] = false;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		edPass.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (edPass.getText().toString().length() >= 6) {
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_synced);
					drawable.setBounds(0, 0, 60, 60);
//					if(ifboo[1]){
//						edPass.setCompoundDrawables(null, null, drawable, null);
//						return ;
//					}
					edPass.setError("正确", drawable);
					ifboo[1] = true;
					
				} else {
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_not_synced);
					drawable.setBounds(0, 0, 60, 60);
					edPass.setError("您输入的密码不得小于6位", drawable);
					ifboo[1] = false;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		edNewPass.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (edNewPass.getText().toString().length() >= 6) {
					if (edPass.getText().toString()
							.equals(edNewPass.getText().toString())) {
						Drawable drawable = getResources().getDrawable(
								RProxy.registeract2_offline_notebook_synced);
						drawable.setBounds(0, 0, 60, 60);
//						if(ifboo[2]){
//							edNewPass.setCompoundDrawables(null, null, drawable, null);
//							return ;
//						}
						edNewPass.setError("正确", drawable);
						ifboo[2] = true;
					} else {
						Drawable drawable = getResources()
								.getDrawable(
										RProxy.registeract2_offline_notebook_not_synced);
						drawable.setBounds(0, 0, 60, 60);
						edNewPass.setError("您两次输入的密码不相同", drawable);
						ifboo[2] = false;
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		edCode.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (edCode.getText().toString().length() == 6) {
					if (edCode.getText().toString().equals(codeKey)) {
						Drawable drawable = getResources().getDrawable(
								RProxy.registeract2_offline_notebook_synced);
						drawable.setBounds(0, 0, 60, 60);
//						if(ifboo[3]){
//							edCode.setCompoundDrawables(null, null, drawable, null);
//							return ;
//						}
						edCode.setError("正确", drawable);
						ifboo[3] = true;
						submit.setEnabled(true);
					} else {
						Drawable drawable = getResources()
								.getDrawable(
										RProxy.registeract2_offline_notebook_not_synced);
						drawable.setBounds(0, 0, 60, 60);
						edCode.setError("您输入的验证码不正确", drawable);
						ifboo[3] = false;
						submit.setEnabled(false) ;
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		// edPhone.setOnFocusChangeListener(new OnFocusChangeListener() {
		//
		// @Override
		// public void onFocusChange(View v, boolean hasFocus) {
		// if (edPhone.hasFocus() == false) {
		// phoneIF.setVisibility(View.VISIBLE);
		// edPhone.setCompoundDrawables(null, null, null, null);
		// ifPhone();
		// }
		//
		// }
		// });

		// edPass.setOnFocusChangeListener(new OnFocusChangeListener() {
		//
		// @Override
		// public void onFocusChange(View v, boolean hasFocus) {
		// if (edPass.hasFocus() == false) {
		// if (edPass.getText().toString().length() < 6) {
		// Drawable drawable = getResources().getDrawable(
		// RProxy.registeract2_offline_notebook_not_synced);
		// drawable.setBounds(0, 0, 60, 60);
		// edPass.setError("您输入的密码不得小于6位", drawable);
		// ifboo[1] = false;
		// } else {
		// Drawable drawable = getResources().getDrawable(
		// RProxy.registeract2_offline_notebook_synced);
		// drawable.setBounds(0, 0, 60, 60);
		// edPass.setCompoundDrawables(null, null, drawable, null);
		// ifboo[1] = true;
		// }
		// }
		//
		// }
		// });

		// edNewPass.setOnFocusChangeListener(new OnFocusChangeListener() {
		//
		// @Override
		// public void onFocusChange(View v, boolean hasFocus) {
		//
		// if (edNewPass.hasFocus() == false) {
		// if (edNewPass.getText().toString().equals("")) {
		// Drawable drawable = getResources().getDrawable(
		// RProxy.registeract2_offline_notebook_not_synced);
		// drawable.setBounds(0, 0, 60, 60);
		// edNewPass.setError("请输入密码", drawable);
		// ifboo[2] = false;
		// } else {
		// if (edPass.getText().toString()
		// .equals(edNewPass.getText().toString())) {
		// Drawable drawable = getResources().getDrawable(
		// RProxy.registeract2_offline_notebook_synced);
		// drawable.setBounds(0, 0, 60, 60);
		// edNewPass.setCompoundDrawables(null, null,
		// drawable, null);
		// ifboo[2] = true;
		// } else {
		// Drawable drawable = getResources().getDrawable(
		// RProxy.registeract2_offline_notebook_not_synced);
		// drawable.setBounds(0, 0, 60, 60);
		// edNewPass.setError("您两次输入的密码不相同", drawable);
		// ifboo[2] = false;
		// }
		// }
		// }
		//
		// }
		// });

		// edCode.setOnFocusChangeListener(new OnFocusChangeListener() {
		//
		// @Override
		// public void onFocusChange(View v, boolean hasFocus) {
		// if (edCode.hasFocus() == false) {
		// if (edCode.getText().toString().equals(codeKey)) {
		// Drawable drawable = getResources().getDrawable(
		// RProxy.registeract2_offline_notebook_synced);
		// drawable.setBounds(0, 0, 60, 60);
		// edCode.setCompoundDrawables(null, null, drawable, null);
		// ifboo[3] = true;
		// } else {
		// Drawable drawable = getResources().getDrawable(
		// RProxy.registeract2_offline_notebook_not_synced);
		// drawable.setBounds(0, 0, 60, 60);
		// edCode.setError("您输入的验证码不正确", drawable);
		// ifboo[3] = false;
		// }
		// }
		//
		// }
		// });
	}

	private void ifPhone() {
		JSONObject js = new JSONObject();
		try {
			js.put("phone", edPhone.getText().toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RegisterPhoneIFHTTP http = new RegisterPhoneIFHTTP(
				getApplicationContext(), js);
		http.handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.arg1) {

				case 0: {
					phoneIF.setVisibility(View.GONE);
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_synced);
					drawable.setBounds(0, 0, 60, 60);
					edPhone.setCompoundDrawables(null, null, drawable, null);
					ifCode();
					ifboo[0] = true;
				}

					break;
				case 4: {
					phoneIF.setVisibility(View.GONE);
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_not_synced);
					drawable.setBounds(0, 0, 60, 60);
					edPhone.setError("您的手机号已经被注册了", drawable);
					ifboo[0] = false;
				}

					break;
				case 2: {
					phoneIF.setVisibility(View.GONE);
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_not_synced);
					drawable.setBounds(0, 0, 60, 60);
					edPhone.setError("您的手机号有误请检查", drawable);
					ifboo[0] = false;
				}

					break;
				case 1: {
					phoneIF.setVisibility(View.GONE);
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_not_synced);
					drawable.setBounds(0, 0, 60, 60);
					edPhone.setError("您的手机号不能为空", drawable);
					ifboo[0] = false;
				}

					break;

				default: {
					phoneIF.setVisibility(View.GONE);
					Drawable drawable = getResources().getDrawable(
							RProxy.registeract2_offline_notebook_not_synced);
					drawable.setBounds(0, 0, 60, 60);
					edPhone.setError("验证发现系统级错误，请稍后再试！", drawable);
					ifboo[0] = false;
				}
					break;
				}
			}
		};
		http.sendData();
	}

	private void ifCode() {
		JSONObject js = new JSONObject();
		try {
			js.put("mobile", edPhone.getText().toString());
			js.put("flag", "0");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RegisterCodeIFHTTP http = new RegisterCodeIFHTTP(
				getApplicationContext(), js);
		http.handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (0 == msg.arg1) {
					RegusteractCode.getInstance().setCode((String) msg.obj);
					codeKey = RegusteractCode.getInstance().getCode();
					imgCode.setImageBitmap(RegusteractCode.getInstance()
							.createBitmap());
				} else {
					imgCode.setImageResource(RProxy.registeract2_code);
					Toast.makeText(getApplicationContext(),
							"验证码请求失败，点击验证码图片尝试重新索取！", Toast.LENGTH_SHORT)
							.show();
				}
			}
		};
		http.sendData();

	}

	private void ifSubmit() {
		JSONObject js = new JSONObject();
		try {
			js.put("mobile", edPhone.getText().toString());
			js.put("pwd", edNewPass.getText().toString());
			js.put("verify_code", edCode.getText().toString());
			js.put("app_id", MyInfoUtil.getAppInfo(MyApplication.get()).app_id);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RegisterHTTP http = new RegisterHTTP(getApplicationContext(), js);
		http.handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.arg1 == 0) {
					registerSuccess((String) msg.obj);
					Toast.makeText(getApplicationContext(), "注册成功!",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(), "注册失败，请重试!",
							Toast.LENGTH_SHORT).show();
				}
			}
		};
		http.sendData();
	}

	public void showpwd(View view) {
		CheckBox cb = (CheckBox) findViewById(RProxy.registeract_showpwd_chk);
		if (cb.isChecked()) {
			edPass.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
			edNewPass.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
		} else {
			edPass.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
			edNewPass.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
		}
	}

	public void register(View view) {
		ifSubmit();
	}

	public void back(View view) {
		finish();
		goLoginAct(null);
	}

	public void registerSuccess(String jid) {
		String mobile = edPhone.getText().toString().trim();
		PreferencesUtils.setPfValue(getApplicationContext(),
				Constants.ACCOUNT_BAREJID_KEY, jid, String.class.getName());
		PreferencesUtils.setPfValue(getApplicationContext(),
				Constants.ACCOUNT_USER_MOBILE, mobile, String.class.getName());
		PreferencesUtils.setPfValue(getApplicationContext(),
				Constants.ACCOUNT_PASSWORD_KEY, edPass.getText().toString()
						.trim(), String.class.getName());
		//PreferencesUtils.setPfValue(getApplicationContext(),
		//		Constants.ACCOUNT_VALIDATED, "1", String.class.getName());
		goLoginAct(mobile);
	}

	/* 跳转登陆界面 */
	private void goLoginAct(String mobile) {
		Intent i = new Intent();
		i.setClass(this, LoginAct.class);
		if(mobile!=null)
		i.putExtra("phone", mobile);
		startActivity(i);
		finish();
	}

	// private class NotEmptyTextWatcher implements TextWatcher {
	//
	// @Override
	// public void afterTextChanged(Editable s) {
	//
	// }
	//
	// @Override
	// public void beforeTextChanged(CharSequence s, int start, int count,
	// int after) {
	//
	// }
	//
	// @Override
	// public void onTextChanged(CharSequence s, int start, int before,
	// int count) {
	// for (int i = 0, j = ifboo.length - 1; i < j; i++) {
	// if (!ifboo[i]) {
	// submit.setEnabled(false) ;
	// return;
	// }
	// }
	// if (edCode.getText().toString().equals(codeKey)) {
	// Drawable drawable = getResources().getDrawable(
	// RProxy.registeract2_offline_notebook_synced);
	// drawable.setBounds(0, 0, 60, 60);
	// edCode.setCompoundDrawables(null, null, drawable, null);
	// submit.setEnabled(true);
	// }else{
	// submit.setEnabled(false) ;
	// }
	// }
	// }
}